// Using an object literal for a jQuery feature
/*(function () {
	//define the loginView
	var LoginView = Backbone.View.extend({
		
		//container for the view
		el: $('div.row'),

		//handle events
		events: {
			"submit": function(evt) {
				evt.preventDefault();
				var username = $('#username').val();							
				var password = $('#password').val();
				if(username == password) {
					sessionStorage.username = username;
					appRouterInstance.navigate("welcome", {trigger: true});
				}
			}
		},

		//render the login page
		render: function() {
			var template;
			if(sessionStorage.username)
			template = _.template($('#loginTemplate').html(), {uname: sessionStorage.username})
			else
			template = _.template($('#loginTemplate').html(), {uname: ""});
				
			$('div.row').html(template);						
		}
	});

	//define the welcomeView
	var WelcomeView = Backbone.View.extend({

		//container for the view
		el: $('div.row'),

		//handle events
		events: {
			"click #backButton": function(evt) {
				appRouterInstance.navigate("", {trigger: true});
			}
		},

		//render the welcome page
		render: function() {
			if(sessionStorage.username) {
				var template = _.template($('#welcomeTemplate').html(), {name: sessionStorage.username});
				$('div.row').html(template);
			} else {
				alert('Username not defined');
			}
		}
	});

	var loginViewInstance = new LoginView();
	var welcomeViewInstance = new WelcomeView();

	//Define the Application Router
	var AppRouter = Backbone.Router.extend({ 
		routes: {
			"": "index",
			"welcome": "welcome"
		},					
		index: function() {
			loginViewInstance.render();
			
		},
		welcome: function() {
			welcomeViewInstance.render();
		}
	});

	var appRouterInstance = new AppRouter();
	Backbone.history.start();
})();
Backbone.View.prototype.close = function () {
    if (this.beforeClose) {
        this.beforeClose();
    }
    this.remove();
    this.unbind();
};*/
var backBoneObj = (function() {
	var construct = function() {
		window.App = {
			Models: {},
			Collections: {},
			Views: {},
			Router: {}
		};
		App.Router = Backbone.Router.extend({
			routes: {
				 '*path': 'defaultRoute'
			},
			defaultRoute: function(path){
				//alert(path);
				//$(document.body).append("Index route has been called.."+path);
				if(path != null){
					$('body > #js-nav').find("li.active").removeClass('active');
					//$('#js-right-nav').find("li.active").removeClass('active');
					$('body > #js-nav').find("a[href^='/"+path+"']").first().parent('li').addClass('active');
					//$('#js-right-nav').find("a[href^='/"+path+"']").first().parent('li').addClass('active');
					ajaxCall('/'+path);
				}
			}
		});
		window.app_router = new App.Router;
		Backbone.history.start();
	};
	var ajaxCall = function(url)
	{
		$.blockUI();
		var request = $.ajax({
			url: url,
			type: "GET",
			dataType: "html",
		   xhr: function()
		   {
			    var xhr = new window.XMLHttpRequest();
			 //Download progress
			 xhr.addEventListener("progress", function(evt){console.log('progress called');
			   if (evt.lengthComputable) {
				 var percentComplete = evt.loaded / evt.total;
				 //Do something with download progress
				 console.log(percentComplete);
			   }
			 }, false);
			 return xhr;
		   },
		});
		request.done(ajaxDone);
		request.fail(ajaxFail);
	};
	var ajaxDone = function(response)
	{
		$('body > .js-response').html(response);
		document.title = $('#js-page-title').html();
		$.unblockUI();
		//$('#page > .js-response').ready(OnReady.triggerevants);
	};
	var ajaxFail = function(jqXHR, textStatus)
	{
		$.unblockUI(); 
	};
    // public API
    return {
        construct: construct
    };
})();
var OnReady = {
	target :'body > .js-response',
	that : null,
    init: function( settings ) {
        OnReady.config = {};
        //allow overriding the default config
        $.extend( OnReady.config, settings );
        OnReady.setup();
    },
    setup: function() {
		backBoneObj.construct();
		$('body').on("click", "a", OnReady.OnClicked);
		$('body').on("submit", "form.js-ajax-form", OnReady.OnFormSubmit);
    },
	triggerevants: function() {
		$('body').on("submit", "form.js-ajax-form", OnReady.OnFormSubmit);
    },
	OnClicked : function(evant) {
		var $this = $(this);
		//console.log($this.hasClass('js-normal-link'));
		if ($this.hasClass('js-normal-link')) {
		}
		else {
			var href = { prop: $this.prop("href"), attr: $this.attr("href") };
			//Get the absolute root.
			var root = location.protocol + "//" + location.host + CFG.baseUrl;
			// Ensure the root is part of the anchor href, meaning it's relative.
			//console.log(href.prop);
			//console.log(href.attr);
			//console.log(Backbone.history.fragment);
			var temp_frag = Backbone.history.fragment;
			// Stop the default event to ensure the link will not cause a page
			// refresh.
			evant.preventDefault();
			// `Backbone.history.navigate` is sufficient for all Routers and will
			// trigger the correct events. The Router's internal `navigate` method
			// calls this anyways.  The fragment is sliced from the root.
			Backbone.history.navigate(href.attr, {trigger:true});
			if(temp_frag == Backbone.history.fragment)
				Backbone.history.loadUrl(Backbone.history.fragment);
		}
	},
	OnFormSubmit : function(evant) {
		var $this = $(this);
		$.blockUI();
		$this.ajaxSubmit({target:OnReady.target,beforeSubmit: OnReady.beforeAjaxSubmit,success:OnReady.successfulAjaxSubmit});
		return false;
	},
	beforeAjaxSubmit : function(formData, jqForm, options){
		return true;
	},
	successfulAjaxSubmit : function(responseText, statusText, xhr, $form) {
		$.unblockUI(); 
	}
};
$(document).ready(OnReady.init);